package com.duniptech.soa.util;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class MyCompiler {
	protected StringBuffer console;
	
	public MyCompiler() {
		console = new StringBuffer();
	}
	
	public boolean compile(List<String> filePaths) throws Exception {
		console.delete(0, console.length());
	    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
	    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
	    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(filePaths);
	    String jars = "";
		File dir = new File(Util.LIB_DIR);
		//File dir = new File("C:/axis2-1.3/lib");
		String[] children = dir.list();
		for(int i=0; i< children.length; i++) {
			if(children[i].indexOf(".jar")>=0) {
				File file = new File(Util.LIB_DIR + File.separator + children[i]);
				jars += Util.CLASSPATH_SEPARATOR + file.getAbsolutePath();
			}
		}
	    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, Arrays.asList("-classpath",Util.LIB_DIR + File.separator + "devsjava.jar" + jars, "-d", Util.CLASSES_DIR), null, compilationUnits);
	    boolean success = task.call();
	    for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
	    	console.append("Code: ");
	    	console.append(diagnostic.getCode());
	    	console.append("\n");
	    	console.append("Kind: ");
	    	console.append(diagnostic.getKind());
	    	console.append("\n");
	    	console.append("Position: ");
	    	console.append(diagnostic.getPosition());
	    	console.append("\n");
	    	console.append("Start Position: ");
	    	console.append(diagnostic.getStartPosition());
	    	console.append("\n");
	    	console.append("End Position: ");
	    	console.append(diagnostic.getEndPosition());
	    	console.append("\n");
	    	console.append("Source: ");
	    	console.append(diagnostic.getSource());
	    	console.append("\n");
	    	console.append("Message: ");
	    	console.append(diagnostic.getMessage(null));
	    	console.append("\n");
	    	fileManager.close();
	    	console.append("Success: " + success + "\n");
	    }
		return success;
	}
	
	public String getOutput() { return console.toString(); }
}
